﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using InHD.model;
using InHD.utilities;
using System.Data;

namespace InHD.dataaccess
{
    class ManagementUnitRepository
    {
        #region Fields

        readonly List<ManagementUnit> _mngUnitCollection;
        //For DB Utils
        private DBUltils _db;
        string[] _paramName;
        string[] _value;
        DBUltils.ParamType[] _paramType;

        #endregion // Fields

        #region Constructor

        /// <summary>
        /// Creates a new repository of 
        /// </summary>
        public ManagementUnitRepository()
        {
            _mngUnitCollection = new List<ManagementUnit>();
            this._db = new DBUltils();
            if (!_db.connectDB(Constants.Security.DefaultDBUser, Constants.Security.DefaultDBPassword))
                throw new ArgumentNullException(Constants.Messages.CannotConnectDB);
        }

        public string LoadAllMngUnit()
        {
            try
            {
                if (_db == null)
                    throw new ArgumentNullException(Constants.Messages.DBNotInitialized);
                DataSet ds;
                ds = _db.queryDB("[GetAllMngUnit]", _paramName, _paramType, _value, DBUltils.QueryType.Select);
                if (ds != null && ds.Tables[0] != null)
                {
                    this._mngUnitCollection.Clear();
                    DataTable table = ds.Tables[0];
                    foreach (DataRow row in table.Rows)
                    {
                        int tmpID = Convert.ToInt16(row["id"]);
                        string tmpMngUnitUNK = Convert.ToString(row["mngUNK"]);
                        string tmpName = Convert.ToString(row["name"]);
                        this._mngUnitCollection.Add(ManagementUnit.CreateNewManageMentUnit(tmpMngUnitUNK, tmpName));
                    }
                }
            }
            catch (Exception e)
            {
                Logger.RecordMessage(e, MessageType.Error);
                return e.Message;
            }
            return string.Empty;
        }

        public List<ManagementUnit> GetMngUnitCollection()
        {
            return this._mngUnitCollection;
        }

        #endregion // Constructor
    }
}
